import {Object3D, LoadingManager, Matrix4, Euler, Vector3} from "three";
// let FBXLoader = require('three-fbxloader-offical')
// import * as THREE from "three";
let THREE=require('three');
import {FBXLoader} from "three/examples/jsm/loaders/FBXLoader.js"
import {TGALoader} from "three/examples/jsm/loaders/TGALoader"
import {LoaderUtils} from "three/build/three.module";


export class ProductMgr {

  constructor() {
    this.root = new Object3D();
    this.products = {};
    console.log("ProductMgr constructor");
    // let func = THREE.LoaderUtils.extractUrlBase;
    // THREE.LoaderUtils.extractUrlBase = function (url) { return func(url) + "Texture2D/"; }
  }


  loadThreeJson(products, fbxUrl){

    for (let index = 0; index < products.length; index++) {
      const product = products[index];
      this.mergeFbxs(product, fbxUrl);
    }
    this.startLoadjson();
  }


  startLoadjson() {
    for (const key in this.products) {
      // if ((key.indexOf("331111111111114") >= 0))
      this.loadJson(key, this.products[key]);
    }
  }


  loadJson(url, products){
    let loader = new THREE.ObjectLoader(new LoadingManager());
    // loader.setCrossOrigin('Anonymous')
    // console.log(loader.crossOrigin);
    console.log(loader.manager);
    loader.resourcePath = LoaderUtils.extractUrlBase(url) + "Texture2D/";
    console.log(url);
    console.log(loader.resourcePath);
    let tgaLoader = new TGALoader();
    tgaLoader.setPath(loader.resourcePath);
    // THREE.Loader.Handlers.add(/\.tga$/i, tgaLoader);
    loader.manager.addHandler(/\.tga$/i, tgaLoader)
    let root = this.root;
    let mgr = this;
    loader.load(url, function (object) {
      console.log("加载成功 : " + url);
      for (let index = 0; index < products.length; index++) {
        const product = products[index];
        console.log(product);
        console.log(mgr);
        let obj = object.clone();
        let matrix = mgr.calMatrix(product.T, product.R, product.S);
        obj.applyMatrix4(matrix);
        console.log("角度 %s", JSON.stringify(obj.rotation.toVector3()));
        console.log("位置 %s", JSON.stringify(obj.position));
        obj.traverse(function (child) {
          if (child.isMesh) {
            // console.log((child.material.emissive));
            // child.material.emissive.set(1, 1, 1);
            // console.log(JSON.stringify(child.material));
            child.castShadow = true;
            child.receiveShadow = true;
            child.material.color.set(0xffffff);
            child.material.bumpScale = 0;
          }
        });
        root.add(obj)
      }
    }, null, function (e) {
      console.log(url + "加载失败");
      console.log(e);
    });
  }


  //旧版本load
  load(products, fbxUrl) {
    for (let index = 0; index < products.length; index++) {
      const product = products[index];
      this.mergeFbxs(product, fbxUrl);
    }
    this.startLoad();
  }

  //处理url
  mergeFbxs(product, fbxUrl) {
    var name = product.Url.split("/")[1]
    // var url = "http://iddd.oss-cn-shanghai.aliyuncs.com/sheji/public/model/" + product.Url + "/" + name + ".fbx"
    // var url = "http://192.168.1.188:10077/" + name + "/" + name + ".fbx";
    var url = fbxUrl + product.Url + "/" + name + ".fbx"
    if (this.products[url] == null)
      this.products[url] = []
    this.products[url].push(product);
  }

  //旧版本加载
  startLoad() {
    for (const key in this.products) {
      // if ((key.indexOf("331111111111114") >= 0))
      this.loadFbx(key, this.products[key]);
    }
  }

  //旧版本加载fbx
  loadFbx(url, products) {
    let loader = new FBXLoader(new LoadingManager());
    // loader.setCrossOrigin('Anonymous')
    // console.log(loader.crossOrigin);
    console.log(loader.manager);
    loader.resourcePath = LoaderUtils.extractUrlBase(url) + "Texture2D/";
    console.log(url);
    console.log(loader.resourcePath);
    let tgaLoader = new TGALoader();
    tgaLoader.setPath(loader.resourcePath);
    // THREE.Loader.Handlers.add(/\.tga$/i, tgaLoader);
    loader.manager.addHandler(/\.tga$/i, tgaLoader)
    let root = this.root;
    let mgr = this;
    loader.load(url, function (object) {
      console.log("加载成功 : " + url);
      for (let index = 0; index < products.length; index++) {
        const product = products[index];
        console.log(product);
        console.log(mgr);
        let obj = object.clone();
        let matrix = mgr.calMatrix(product.T, product.R, product.S);
        obj.applyMatrix4(matrix);
        console.log("角度 %s", JSON.stringify(obj.rotation.toVector3()));
        console.log("位置 %s", JSON.stringify(obj.position));
        obj.traverse(function (child) {
          if (child.isMesh) {
            // console.log((child.material.emissive));
            // child.material.emissive.set(1, 1, 1);
            // console.log(JSON.stringify(child.material));
            child.castShadow = true;
            child.receiveShadow = true;
            child.material.color.set(0xffffff);
            child.material.bumpScale = 0;
          }
        });
        root.add(obj)
      }
    }, null, function (e) {
      console.log(url + "加载失败");
      console.log(e);
    });
  }

  //新版本处理url,返回多个promise对象
  loadAsync(products, fbxUrl) {
    let fbxPromiseArr = []
    for (let index = 0; index < products.length; index++) {
      const product = products[index];
      var name = product.Url.split("/")[1]
      var url = fbxUrl + product.Url + "/" + name + ".fbx"
      if (this.products[url] == null)
        this.products[url] = []
      this.products[url].push(product);
      let fbxP = this.loadFbxAsync(url);
      fbxPromiseArr.push(fbxP);
    }
    return Promise.all(fbxPromiseArr);
  }

  //新版本加载fbx
  loadFbxAsync(url) {
    let loader = new FBXLoader(new LoadingManager());
    // loader.setCrossOrigin('Anonymous')
    // console.log(loader.crossOrigin);
    console.log(loader.manager);
    loader.resourcePath = LoaderUtils.extractUrlBase(url) + "Texture2D/";
    console.log(url);
    console.log(loader.resourcePath);
    let tgaLoader = new TGALoader();
    tgaLoader.setPath(loader.resourcePath);
    // THREE.Loader.Handlers.add(/\.tga$/i, tgaLoader);
    loader.manager.addHandler(/\.tga$/i, tgaLoader)
    return loader.loadAsync(url);
  }


  /**
   * 根据unity中的坐标旋转缩放计算它最终在3s中的矩阵
   * @param {*} p
   * @param {*} r
   * @param {*} s
   */
  calMatrix(p, r, s) {
    console.log(" unity角度 %s ", JSON.stringify(r));
    //构造unity的矩阵
    let rotationMatrix = new Matrix4();
    let euler = new Euler();
    euler.set(THREE.MathUtils.degToRad(r.x), THREE.MathUtils.degToRad(r.y), THREE.MathUtils.degToRad(r.z), "ZXY");
    rotationMatrix.makeRotationFromEuler(euler);

    let tranlaterMatrix = new Matrix4();
    tranlaterMatrix.setPosition(p.x, p.y, p.z);

    //fbx比原始的要大100倍
    let scale = 0.01;
    let scaleMatrix = new Matrix4();
    scaleMatrix.makeScale(s.x * scale, s.y * scale, s.z * scale);

    let unityMatrix = scaleMatrix.premultiply(rotationMatrix);
    unityMatrix = unityMatrix.premultiply(tranlaterMatrix);

    //求unity到3d的转换矩阵
    let basicMatrix = new Matrix4();
    basicMatrix.makeBasis(new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, -1));

    //将unity矩阵转换为3s矩阵
    let matrix = basicMatrix.clone().premultiply(unityMatrix);
    matrix = matrix.premultiply(basicMatrix.clone());

    return matrix;
  }

}
